//
//  DiscussDetailView.m
//  OperationPro
//
//  Created by Mac on 16/10/9.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "DiscussDetailView.h"
#import "DiscussDetailModel.h"
#import "DiscussDetailCell.h"
#import "SDImageCache.h"
#import "UIImageView+WebCache.h"
#import "InvitationModel.h"
#import "LoadingView.h"
@interface DiscussDetailView()
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) NSMutableArray *discussData;
@property (nonatomic, strong) NSMutableArray *totalData;
@property(nonatomic,strong)InvitationModel *model;

@property (nonatomic, strong) NSString *uuid;
@property (nonatomic, strong) NSString *describe;
@property (nonatomic, strong) NSString *imageString;
@property (nonatomic) BOOL isWarnuiud;
@property (nonatomic, strong) NSString *warnuiud;
@end

@implementation DiscussDetailView
- (instancetype)initWithFrame:(CGRect)frame withdataModel:(InvitationModel *)model withImageString:(NSString *)imageString withDescribe:(NSString *)describe withIsWarnuiud:(BOOL)isWarnuiud withWarnuiud:(NSString*)warnuiud{
    self.isWarnuiud=isWarnuiud;
    self.model = model;
    self.warnuiud=warnuiud;
    self.uuid=model.I_uuid;
    self.describe=describe;
    self.imageString=imageString;
    self = [super initWithFrame:frame style:UITableViewStylePlain];
    if (self) {
        
    }
    return self;
}

- (void)initData{
    [super initData];
    _totalData = [NSMutableArray arrayWithObjects:@{}, @{}, nil];
}

- (UIView *)topView{
    if (_topView == nil) {

        echo(([NSString stringWithFormat:@"=====%@",self.model]));
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WindowWidth, 110)];
        [_topView setBackgroundColor:[UIColor whiteColor]];
       //头像和名字内容

        UIImageView *topImg=[[UIImageView alloc]init];
        [_topView addSubview:topImg];
        [topImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_topView).mas_offset(20);
            make.top.equalTo(_topView).mas_offset(20);
            make.size.mas_equalTo(CGSizeMake(50, 50));
        }];
        topImg.layer.masksToBounds=YES;
        topImg.layer.cornerRadius=25;
        NSString*urlString =[CClass getCacheData:qnDomain];
        if (self.model.I_headImg==nil||[self.model.I_headImg isEqualToString:@""]) {
            topImg.image=[UIImage imageNamed:@"Ico_home_head"];
            
        }else
        {
            NSURL *headUrl =[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",urlString,self.model.I_headImg]];
            [topImg sd_setImageWithURL:headUrl placeholderImage:[UIImage imageNamed:@"Ico_home_head"]];
            
        }
        //名字
        UILabel *lblName = [[UILabel alloc] init];
        [_topView addSubview:lblName];
        [lblName mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(topImg.mas_right).mas_offset(10);
            make.top.equalTo(topImg);
        }];
        lblName.tag = 101;
        lblName.font = F(10);
        lblName.textColor =LightFontColor;
       
        //时间
        UILabel *lblDate = [[UILabel alloc] init];
        [_topView addSubview:lblDate];
        [lblDate mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_topView).mas_offset(-20);
            make.bottom.equalTo(lblName);
        }];
        lblDate.textColor =LightFontColor;
        lblDate.font = F(10);
        lblDate.tag = 102;

        //标题
        UILabel *lblTitle = [[UILabel alloc] init];
        [_topView addSubview:lblTitle];
        [lblTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(lblName);
            make.right.equalTo(_topView).mas_offset(-10);
            make.top.equalTo(lblName.mas_bottom).mas_offset(14);
        }];
        lblTitle.tag = 100;
        lblTitle.textColor = FontColor;
        lblTitle.font = F(14);
        lblTitle.numberOfLines = 0;
      
        //详细内容
        UILabel *lblDes = [[UILabel alloc] init];
        [_topView addSubview:lblDes];

        lblDes.tag = 103;
        lblDes.font = F(10);
        lblDes.textColor = LightFontColor;
        lblDes.numberOfLines = 0;
        //标题
        if ((self.model.I_kind==nil||[self.model.I_kind isEqualToString:@""])) {
            lblTitle.text = [NSString stringWithFormat:@"%@", self.model.I_kind];
        }else
        {
            NSString *kind ;
            if ([self.model.I_kind isEqualToString:@"01"]) {
                kind=@"提问";
                
            }else if ([self.model.I_kind isEqualToString:@"02"]) {
                kind=@"讨论";
                
            }else if ([self.model.I_kind isEqualToString:@"03"]) {
                kind=@"经验";
                
                
            }
            lblTitle.text = [NSString stringWithFormat:@"[%@]%@", kind, self.model.I_title];
//            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:lblTitle.text];
//            [attr addAttributes:@{NSForegroundColorAttributeName:C(@"1cdb09")} range:NSMakeRange(0, kind.length + 2)];
//            lblTitle.attributedText = attr;
        }
        CGSize titleSize = [lblTitle.text sizeWithFont:lblTitle.font constrainedToSize:CGSizeMake(WindowWidth - 40, 1000)];
       CGFloat  headHeight=  MAX((titleSize.height+20+12+14+10), 70+10);
        //人名字
        lblName.text =self.model.I_author;
        //时间
        NSString  *a = self.model.I_created;
        NSString *timeString = [a substringWithRange:NSMakeRange(0, 16)];
        lblDate.text = timeString;
        if (self.model.I_content==nil||[self.model.I_content isEqualToString:@""])
        {
            lblDes.text=@"";
        }else
        {
            //详细内容
            lblDes.text=self.model.I_content;
        }
       
       
        //图片
        UIImageView *headImg=[[UIImageView alloc]init];
        [_topView addSubview:headImg];
        
//没有图片的时候
        if (self.model.I_image==nil||[self.model.I_image isEqualToString:@""])
        {
             CGSize contextSize = [lblDes.text sizeWithFont:lblDes.font constrainedToSize:CGSizeMake(WindowWidth - 100, 1000)];
             lblDes.frame=CGRectMake(80, headHeight, _topView.bounds.size.width-100, contextSize.height);
            
            _topView.frame=CGRectMake(0, 0, WindowWidth, headHeight+contextSize.height+10);
        }else
        {
           //有图片的时候
            CGSize contextSize = [lblDes.text sizeWithFont:lblDes.font constrainedToSize:CGSizeMake(WindowWidth - 120, 1000)];
            lblDes.frame=CGRectMake(80, headHeight, _topView.bounds.size.width-100, contextSize.height);
            
            headImg.frame=CGRectMake(80, CGRectGetMaxY(lblDes.frame)+10, 180, 180*3/4);
            NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",[CClass getCacheData:qnDomain],self.model.I_image]];
            [headImg sd_setImageWithURL:url];
       
            headImg.userInteractionEnabled=YES;
            [headImg bk_whenTapped:^{
                [XWScanImage scanBigImageWithImageView:headImg];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"closeKeyboard" object:nil];

            }];
 
       
            _topView.frame=CGRectMake(0, 0, WindowWidth,CGRectGetMaxY(headImg.frame)+10);
            
        }
        
      
      
//不是分享的
        if (self.isWarnuiud==NO) {
            
        }else if(self.isWarnuiud==YES)
        {
        _topView.frame=CGRectMake(0, 0, WindowWidth, CGRectGetMaxY(_topView.frame)+60);
            
        UIView *centerView=[[UIView alloc]initWithFrame:CGRectMake(80, _topView.bounds.size.height-60, WindowWidth-100, 50)];
                centerView.backgroundColor=C(@"eaeaea");
                [_topView addSubview:centerView];
                NSString *str =self.imageString;
                UILabel *lab =[[UILabel alloc]init];
                lab.textColor=C(@"585858");
                [centerView addSubview:lab];
                lab.font=FF(14);
            
                //没有图片的时候 和文字
                if ([str isEqual:[NSNull null]]||[str isEqualToString:@""])
                {
                    lab.frame=CGRectMake(15, 5, WindowWidth-50-30, 40);
                    if ([self.describe isEqual:[NSNull null]]||[self.describe isEqualToString:@""]) {
                        lab.text=@"(非文字报修)";

                    }else
                    {
                        lab.text=self.describe;
                   
                    }
                    
                }else
                {
                    NSArray *array = [str componentsSeparatedByString:@","];
                    UIImageView *ImageView =[[UIImageView alloc]initWithFrame:CGRectMake(10, 5, 40, 40)];
                    NSString * urlString=[CClass getCacheData:qnDomain];
                    NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",urlString,[array objectAtIndex:0]]];
                    [ImageView sd_setImageWithURL:url];
                    [centerView addSubview:ImageView];
                    lab.frame=CGRectMake(55, 5, WindowWidth-50-70, 40);
                    if ([self.describe isEqualToString:@""]) {
                        lab.text=@"(非文字报修)";

                    }else
                    {
                    lab.text=self.describe;
                        
                    }
                    
                }
                [centerView bk_whenTapped:^{
                   
                   
                    if (self.gotoDetail) {
                        self.gotoDetail(self.warnuiud);
                    }
                
                    
                }];
                
                
                }
        
            
        
    }
    UILabel *line=[[UILabel alloc]initWithFrame:CGRectMake(0, _topView.bounds.size.height-0.5, WindowWidth, 0.5)];
    line.backgroundColor=LineColor;
    [_topView addSubview:line];
    
    return _topView;
}


- (void)initView{
    [super initView];
    [self registerCell:[DiscussDetailCell class] withModel:[DiscussDetailModel class]];
    self.tableActionType = CTableActionType_Both;
    self.tableHeaderView = self.topView;

    [self setDataWithUrl:@"discuss_replyList" andParam:@{@"uuid":self.uuid}];
    [self refresh];
    [self setShowNoData:NO];
}
- (void)refresh{

    [CClass HttpRequestTask:NO withUrl:@"discuss_replyListHot" withData:@{@"uuid":self.uuid} notifyError:NO onSuccess:^(BaseModel *model) {
        _discussData = [DiscussDetailModel arrayOfModelsFromDictionaries:model.B_data[@"list"] error:nil];
        [self reloadData];
    } onError:^(BaseModel *model) {
        
    }];
    [super refresh];
}

- (void)reloadData{
    if (_discussData) {
        [_totalData replaceObjectAtIndex:0 withObject:_discussData];
    }
    if (self.mainData) {
        [_totalData replaceObjectAtIndex:1 withObject:self.mainData];
    }
    [super reloadData];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"closeKeyboard" object:nil];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _totalData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_totalData[section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [DiscussDetailCell getCellHeightByModel:[self getRowData:indexPath]];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return [_totalData[section] count] == 0 ? 0 : 44;
//    return 44;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WindowWidth, 10)];
    [view setBackgroundColor:[UIColor clearColor]];
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if ([_totalData[section] count] == 0) {
        return nil;
    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WindowWidth, 44)];
    [view setBackgroundColor:[UIColor whiteColor]];
    UILabel *line=[[UILabel alloc]initWithFrame:CGRectMake(0,0, WindowWidth, 0.5)];
    line.backgroundColor=LineColor;
    [view addSubview:line];
    UILabel *lblTitle = [[UILabel alloc] init];
    [view addSubview:lblTitle];
    [lblTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view).mas_offset(20);
        make.centerY.equalTo(view);
    }];
    [lblTitle setText:section == 0 ? @"热门评论" : @"最新评论"];
    lblTitle.font = F(14);
    lblTitle.textColor = C(@"878787");
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    Class class = [DiscussDetailCell class];
    NSString *cellID = [NSString stringWithFormat:@"Cell_%@", NSStringFromClass(class)];
    DiscussDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[class alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    [cell setModel:[self getRowData:indexPath]];
    __block typeof(tableView) weakview = tableView;
    __block typeof(self) weakself = self;
    //点赞事件
    [cell setGoodAction:^(DiscussDetailCell *c) {
        NSIndexPath *index = [weakview indexPathForCell:c];
        __block DiscussDetailModel *weakmodel = weakself.totalData[index.section][index.row];
        __block bool istap = [weakmodel.D_thumb_by_me isEqualToString:@"1"];
        [[LoadingView shareLoading] startAnimating];
        [CClass HttpRequestTask:YES withUrl:istap ? @"discuss_unthumb" : @"discuss_thumb" withData:@{@"uuid":weakmodel.D_uuid} notifyError:YES onSuccess:^(BaseModel *model) {
            if(istap == true){
                weakmodel.D_thumb_by_me = @"";
                weakmodel.D_thumb_count = [NSString stringWithFormat:@"%zd", [weakmodel.D_thumb_count integerValue] - 1];
            }else{
                weakmodel.D_thumb_by_me = @"1";
                weakmodel.D_thumb_count = [NSString stringWithFormat:@"%zd", [weakmodel.D_thumb_count integerValue] + 1];
            }
            [weakview reloadData];
//            [weakview reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone];
            [[LoadingView shareLoading] stopAnimating];
        } onError:^(BaseModel *model) {
            [[LoadingView shareLoading] stopAnimating];
        }];
    }];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.CCellSelect) {
        self.CCellSelect([self getRowData:indexPath]);
    }
}

- (id) getRowData:(NSIndexPath *)indexPath{
    return _totalData[indexPath.section][indexPath.row];
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if (self.DiscussDetailBecomeFirstResponse) {
        self.DiscussDetailBecomeFirstResponse();
    }
    [super touchesEnded:touches withEvent:event];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"closeKeyboard" object:nil];

}

@end
